#!/usr/bin/python3

import os
import shutil
import getpass
import datetime
import sqlite3

from templateinfo import startInfo 
from templateinfo import fileDesc 
from templateinfo import funcDesc 
from templateinfo import makefile 
from datedb import CmdDB

username = getpass.getuser()
modulepath = ''
date = datetime.date.today()
param = ""
ret = "TRUE, FALSE"

def ifModulePath():
    curpath = os.getcwd()
    global modulepath
    modulepath = ""

    if curpath.find('autoedit') > 0:
        modulepath += '../'
    elif curpath.find('function') > 0:
        modulepath += './'
    else:
        print('Invalid path.')
        return 0
    return 1

def startTool():
    os.system('clear')
    print(startInfo)

def createMakefile(moduleName: str):
    file = open("Makefile", 'w')
    file.write(makefile % moduleName)

    file.close()

def createHeadfile(moduleName: str, func: str):
    source = f"en{moduleName}{func}.h"
    desc = f"{func} for module {moduleName}."
    filedescription = fileDesc % (source, desc, username, date)

    file = open('inc/' + source, 'w')
    file.write(filedescription)

    headdef = moduleName.upper() + "_" + func.upper()
    file.write(f"#ifndef __EN_" + headdef + "_H__\n")
    file.write(f"#define __EN_" + headdef + "_H__\n")

    apiname = moduleName.capitalize()
    if func == "api":
        opts = ["Test", "Get", "Set"]
        prefix = ["en", "enAPI"]
    elif func == "init":
        opts = [""]
        prefix = ["en"]
    else:
        opts = []
        prefix = []

    file.write("\n")

    func = func.capitalize()
    for pre in prefix:
        for opt in opts:
            funcname = f"{pre}{apiname}{func}{opt}()"
            file.write('VOID ' + funcname + ";\n")
        file.write("\n")


    file.write("\n#endif")
    file.write("/*__EN_" + headdef + "_H__*/\n")
    file.close()

def createSrcfile(moduleName: str, func: str):
    source = f"en{moduleName}{func}.c"
    desc = f"{func} for module {moduleName}."
    filedescription = fileDesc % (source, desc, username, date)

    file = open('src/' + source, 'w')
    file.write(filedescription)

    apiname = moduleName.capitalize()
    if func == "api":
        opts = ["Test", "Get", "Set"]
        prefix = "en"
        file.write(f"#include \"en{moduleName}api.h\"\n")
    elif func == "util":
        opts = ["Test", "Get", "Set"]
        prefix = "enAPI"
        file.write(f"#include \"en{moduleName}api.h\"\n")
    else:
        opts = [""]
        prefix = "en"
        file.write(f"#include \"en{moduleName}{func}.h\"\n")

    file.write(f"#include \"en{moduleName}inc.h\"\n")
    file.write("\n")

    func = func.capitalize()
    for opt in opts:
        funcname = f"{prefix}{apiname}{func}{opt}()"
        desc = f"{opt} {func} for module {moduleName}"
        funcdescription = funcDesc % (funcname, desc, param, ret, username, date) 

        file.write(funcdescription)
        file.write('VOID ' + funcname + "\n{\n\treturn TRUE;\n}\n\n")
        #inc/en{mod}api.h, *defn.h, *glob.h, *inc.h, *init.h, *macro.h, *proto.h, 
        #Makefile
        #add module to function/Makefile

    file.close()

def createSrc(moduleName: str):
    global modulepath
    global date
    global param
    global ret
    os.makedirs('src')
    os.makedirs('inc')
    #create src/en{mod}init.c, *api.c, *util.c, 
    #filename, file description, apis description
    createSrcfile(moduleName, "init")
    createSrcfile(moduleName, "api")
    createSrcfile(moduleName, "util")

    #inc/en{mod}api.h, *defn.h, *glob.h, *inc.h, *init.h, *macro.h, *proto.h, 
    createHeadfile(moduleName, "init")
    createHeadfile(moduleName, "api")
    createHeadfile(moduleName, "inc")
    createHeadfile(moduleName, "defn")
    createHeadfile(moduleName, "glob")
    createHeadfile(moduleName, "macro")
    createHeadfile(moduleName, "proto")

def addCompiling():
    pass

def addDatabase(moduleName: str):
    cmd_db = CmdDB()
    cmd_db.addModcmd(moduleName)

    cmd_db.close()

def delDatabase(moduleName: str) -> int:
    cmd_db = CmdDB()
    ret = cmd_db.delModcmd(moduleName)

    cmd_db.close()
    return ret

def showDatabase(mod: int):
    cmd_db = CmdDB()
    cmd_db.viewCmds(mod)

    cmd_db.close()

def createModule(moduleName: str):
    _ret = ifModulePath()
    if not _ret:
        return

    global modulepath
    modulepath += moduleName
    os.makedirs(modulepath)
    os.chdir(modulepath)

    createSrc(moduleName)

    #Makefile
    createMakefile(moduleName)
    
    #add module to function/Makefile
    addCompiling()

    #add to sqlite3 datebase
    os.chdir("../.autoedit")
    addDatabase(moduleName)

    os.chdir("../")

def cancelModule(moduleName: str):
    pass

def removeModule(moduleName: str):
    os.chdir(".autoedit")
    ret = delDatabase(moduleName)
    if ret != 0:
        os.chdir("../")
        return
    os.chdir("../")
    shutil.rmtree(f"./{moduleName}/")


